/*
 * Copyright (c) 2021. by XuanWu Wireless Technology Co.Ltd.
 *              All rights reserved
 *
 */

package com.gitee.starblues.integration.inject;

import com.gitee.starblues.annotation.PluginInject;
import com.gitee.starblues.integration.user.PluginUser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;

/**
 * @author <a href="mailto:liujiawen@wxchina.com">Jiawen.Liu</a>
 * @version 2.0.0
 * @since 2021/4/20
 */
public class PluginInjector {

    private static Logger LOG = LoggerFactory.getLogger(PluginInjector.class);

    protected PluginUser pluginUser;

    @Autowired
    public void setPluginUser(PluginUser pluginUser) {
        this.pluginUser = pluginUser;
        if (null != pluginUser) {
            int count = 0;
            for (Field declaredField : this.getClass().getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(PluginInject.class)) {
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(this, pluginUser.getBean(declaredField.getType()));
                        count++;
                    } catch (IllegalAccessException e) {
                        LOG.error("can't set field[" + declaredField.getName() + "] by ", e);
                    }
                }
            }
            LOG.info("plugin inject field success {}", count);
        }
    }
}
